package store.lunangangster.nodeflow.rt.element.flow;

import static store.lunangangster.nodeflow.enums.FlowType.FLOW_IF;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import store.lunangangster.nodeflow.core.component.NodeComponent;
import store.lunangangster.nodeflow.enums.FlowType;
import store.lunangangster.nodeflow.rt.DataBus;
import store.lunangangster.nodeflow.rt.element.Executable;
import store.lunangangster.nodeflow.rt.element.Node;

/**
 * 条件执行流
 *
 * @author cwk
 * @version 1.0
 */
public class IfFlow extends Flow {

	// 判断IfFlow是否已经存在else分支。如果存在就无法再添加ELSE/ELSEIF
	private boolean isElse;

	private Executable trueBranch;

	private Executable falseBranch;


	// need no arguments constructor
	public IfFlow() {}

	@Override
	public void execute(Integer slotIndex) {
		Node ifNode = (Node) this.executableList.get(0);
		NodeComponent component = ifNode.getNodeComponent();
		try {
			if (CollUtil.isEmpty(this.executableList)) {
				return;
			}
			// 执行条件节点
			ifNode.execute(slotIndex);
			// 获取result
			boolean result = BooleanUtil.isTrue(
					(Boolean) DataBus.getSlot(slotIndex).getData(component.getIfResultKey()));
			if (result) {
				if (trueBranch != null) {
					trueBranch.execute(slotIndex);
				}
			} else {
				if (falseBranch != null) {
					falseBranch.execute(slotIndex);
				}
			}
		} finally {
			component.removeIfResultKey();
		}
	}

	@Override
	public FlowType getFlowType() {
		return FLOW_IF;
	}

	public boolean isElse() {
		return this.isElse;
	}

	public void setIsElse(boolean isElse) {
		this.isElse = isElse;
	}

	public Executable getTrueBranch() {
		return trueBranch;
	}

	public Executable getFalseBranch() {
		return falseBranch;
	}

	public void setTrueBranch(Executable trueBranch) {
		this.trueBranch = trueBranch;
	}

	public void setFalseBranch(Executable falseBranch) {
		this.falseBranch = falseBranch;
	}

	public void setBranch(Executable trueBranch, Executable falseBranch) {
		this.trueBranch = trueBranch;
		this.falseBranch = falseBranch;
	}
}
